#include <iostream>
#include <fstream>
#include <thread>
#include <chrono>
#include <cstring>
#include <arpa/inet.h>  // Linux 下使用
#include <sys/socket.h>
#include <unistd.h>     // for close()

const char* datFilePath = "/home/wpp/X_xiangSao_0428/data/udp_data4.dat"; // 你的.dat路径
const char* targetIP = "200.100.10.11";      // 接收端 IP，改成你的实际接收程序监听地址
const int targetPort = 61001;            // 接收端口号
const int packetSize = 1200;             // 每包发送字节数
const int intervalMs = 10;               // 每帧间隔（模拟雷达发帧频率）

int main() {
    // 打开 .dat 文件
    std::ifstream datFile(datFilePath, std::ios::binary);
    if (!datFile) {
        std::cerr << "❌ 无法打开文件: " << datFilePath << std::endl;
        return -1;
    }

    // 创建 UDP socket
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        perror("socket");
        return -1;
    }

    // 设置目标地址
    sockaddr_in targetAddr {};
    targetAddr.sin_family = AF_INET;
    targetAddr.sin_port = htons(targetPort);
    inet_pton(AF_INET, targetIP, &targetAddr.sin_addr);

    char buffer[packetSize];
    int packetCount = 0;

    std::cout << "开始发送数据到 " << targetIP << ":" << targetPort << std::endl;

    while (!datFile.eof()) {
        datFile.read(buffer, packetSize);
        std::streamsize bytesRead = datFile.gcount();

        if (bytesRead <= 0) break;

        // 发送数据
        int sent = sendto(sockfd, buffer, bytesRead, 0, (sockaddr*)&targetAddr, sizeof(targetAddr));
        if (sent != bytesRead) {
            std::cerr << "发送错误，实际发送字节数: " << sent << std::endl;
        } else {
            std::cout << "第 " << ++packetCount << " 包已发送，大小: " << sent << " 字节" << std::endl;
        }

        // 模拟时间间隔
        std::this_thread::sleep_for(std::chrono::milliseconds(intervalMs));
    }

    std::cout << "✅ 所有数据发送完成，退出程序。" << std::endl;
    close(sockfd);
    datFile.close();
    return 0;
}
